/*
 * @# FollowCircleServiceImpl.java 2011-12-23 上午10:42:47
 * 
 * Copyright (C) 2010 - 2011 广州羿安信息科技有限公司
 * Guangzhou ianswer information technology co. ltd.
 * 
 * All rights reserved!
 */
package com.ianswer.px.user.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.ianswer.common.orm.PublicDao;
import com.ianswer.common.util.time.SecondsUtils;
import com.ianswer.px.user.entity.Follow;
import com.ianswer.px.user.entity.FollowCircle;
import com.ianswer.px.user.service.FollowCircleService;
import com.ianswer.px.user.service.FollowService;

/**
 * @author pananz
 */
@Service("followCircleService")
public class FollowCircleServiceImpl implements FollowCircleService {

	@Resource(name = "publicDao")
	private PublicDao publicDao;

	@Resource(name = "followService")
	private FollowService followService;

	@Override
	public Follow insert(Long circleId, Follow follow) {
		Long followId = follow.getId();
		if (get(circleId, followId) != null) {
			return null;
		}
		FollowCircle followCircle = new FollowCircle();
		followCircle.setFollowId(followId);
		followCircle.setCircleId(circleId);
		followCircle.setCreatedAt(SecondsUtils.seconds());
		publicDao.insert("followCircle.insert", followCircle);
		operFollow(circleId, follow);
		return follow;
	}

	private void operFollow(Long circleId, Follow follow) {
		List<Long> circleIds = follow.getCircleIds();
		if (CollectionUtils.isEmpty(circleIds)) {
			circleIds = new ArrayList<Long>();
		}

		if (!circleIds.contains(circleId)) {
			circleIds.add(circleId);
		} else if (circleIds.contains(circleId)) {
			circleIds.remove(circleId);
		}
		String circles = StringUtils.join(circleIds, ",");
		follow.setCircles(circles);
		followService.updateCircles(follow);
	}

	@Override
	public FollowCircle get(Long circleId, Long followId) {
		FollowCircle followCircle = new FollowCircle();
		followCircle.setFollowId(followId);
		followCircle.setCircleId(circleId);
		return publicDao.querySingle("followCircle.getFollowCircleByFcId", followCircle);
	}

	@Override
	public Follow delete(Long circleId, Follow follow) {
		FollowCircle followCircle = new FollowCircle();
		followCircle.setFollowId(follow.getId());
		followCircle.setCircleId(circleId);
		publicDao.delete("followCircle.deleteByFcId", followCircle);
		operFollow(circleId, follow);
		return follow;
	}

	@Override
	public void deleteByFollowId(Long followId) {
		publicDao.delete("followCircle.deleteByFollowId", followId);
	}

	@Override
	public void deleteByCircleId(Long circleId) {
		publicDao.delete("followCircle.deleteByCircleId", circleId);
	}

}
